package 实现数据结构.算法;

import java.util.Arrays;

/**
 * @DESC https://leetcode-cn.com/problemset/algorithms/
 * @Author tzq
 * @Date 2019-08-17 17:56
 **/
public class _1_两数之和 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};

        int[] ints = new Solution().twoSum(nums, 22);
        Arrays.stream(ints).forEach(System.out::println);

    }

    static class Solution {

        /**
         * 优雅的实现方式
         *
         * @param nums
         * @param target
         * @return
         */
        public int[] twoSum2(int[] nums, int target) {
            int[] result = new int[2];
            for (int i = 0; i < nums.length; i++) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[j] == target - nums[i]) {
                        return new int[]{i, j};
                    }
                }
            }

            return result;
        }

        /**
         * 简单暴力扫描解法
         *
         * @param nums
         * @param target
         * @return
         */
        public int[] twoSum(int[] nums, int target) {
            int[] result = new int[2];

            for (int i = 0; i < nums.length; i++) {
                for (int j = i + 1; j < nums.length; j++) {
                    int tmp = nums[i] + nums[j];
                    if (tmp == target) {
                        result[0] = i;
                        result[1] = j;
                    }
                }

            }

            return result;
        }
    }
}

